//
//  WBNetworkManager.swift
//  Weibo
//
//  Created by niqiang on 16/7/6.
//  Copyright © 2016年 niqiang. All rights reserved.
//

import UIKit
import AFNetworking

//Swift 的枚举
enum WBHTTPMethod {
    
    case GET
    case POST
}

class WBNetworkManager: AFHTTPSessionManager {
    
    //静态区 常量 闭包
    //第一次访问时，执行闭包，并且将结果保存在shared 常量中
    static let shared: WBNetworkManager = {
    
    //实例化对象
        let instance = WBNetworkManager()
        
        //设置相应序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
       
        //返回对象
        return instance
    }()
    
    // 访问令牌，所有的网络请求，都基于此令牌（登录除外）
    var accessToken: String?  // = "2.00IzHKDD02sthJae72419026nkdmlD"
    
    //用户微博id
    var uid: String? = "2795141482"
    
    //用户账户的懒加载属性
    lazy var userAccount = WBUserAccount()
    
    //用户登录标记[计算性属性]
    var userLogon: Bool {
    return userAccount.access_token != nil
    }
    
    
    //专门负责拼接token的网络请求方法
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion: (json: AnyObject?, isSuccess: Bool)->()){
    
        //处理token 字典
        //判断token是否为nil ，如果为nil 直接返回
//        guard let token = accessToken else {
         guard let token = userAccount.access_token else {
            print("没有token 需要登录")
            
            NotificationCenter.default().post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification),object: nil)
            
            completion(json: nil, isSuccess: false)
            
            return
        }
        
        // 1判断 参数字典是否存在，如果我nil 应该新建一个字典
        var parameters = parameters
        if parameters == nil {
            //实例化字典
            parameters = [String: AnyObject]()
        }
        
        //2设置参数字典，代码在此处字典一点有值
        parameters!["access_token"] = token
        
        //调用request发起真正的网络请求方法
        request(URLString: URLString, parameters: parameters, completion: completion)
    }
    
    
    //使用一个方法封装AFN的 get post 请求
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion: (json: AnyObject?, isSuccess: Bool)->()  ){
        
        // 成功回调
        let success = { (task: URLSessionDataTask, json: AnyObject?) -> () in
            completion(json: json, isSuccess: true)
        }
        
        // 失败回调
        let failure = { (task: URLSessionDataTask?, error: NSError) -> () in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("Token 过期了")
                
                //发送通知，提示用户再次登录
                NotificationCenter.default().post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification),object: "bad token")
            }
            print("请求错误\(error)")
            
            completion(json: nil, isSuccess: false)
            
        }
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
}
